<template>
	<view class="page-container">
		<view class="navbar" :style="{ backgroundColor: isScrollUp ? '#CCC' : '', paddingTop: 80 + 'rpx' }">
			<!-- 左侧：返回按钮 + 搜索输入框（滚动时显示） -->
			<view class="" style="display: flex">
				<view class="navbar_left">
					<view class="navbar_back" @click="navigateBack">
						<uni-icons type="left" size="32rpx"></uni-icons>
					</view>
					<!-- 搜索输入框：滚动超过阈值时显示 -->
				</view>
				<view class="navbar_right">
					<!-- 搜索图标：未滚动时显示，点击也可触发输入框显示 -->
					<view class="navbar_search" @touchend.prevent="handleSearchInput" v-if="!isScrollUp">
						<uni-icons type="search" size="32rpx"></uni-icons>
					</view>
					<view class="search_box" v-if="isScrollUp" @touchend.prevent="handleSearchInput">
						<input class="search_input" type="search" placeholder="搜索商品..." />
					</view>

					<view class="navbar_edit" @click="handleEdit">
						<uni-icons type="gear" size="32rpx"></uni-icons>
					</view>
				</view>
			</view>

			<!-- 中间：详情菜单（滚动超过阈值时显示） -->
			<view class="detail_menu" v-if="isScrollUp">
				<view class="menu_item" :class="{ active: currentMenu === 'info' }" @click="switchMenu('info')">
					<text>商品详情</text>
				</view>
				<view class="menu_item" :class="{ active: currentMenu === 'images' }" @click="switchMenu('images')">
					<text>图片</text>
				</view>
				<view class="menu_item" :class="{ active: currentMenu === 'price' }" @click="switchMenu('price')">
					<text>详价</text>
				</view>
			</view>

			<!-- 右侧：搜索图标（未滚动时显示） + 编辑按钮 -->
		</view>

		<!-- 主滚动区：包含商品图片 + 所有详情内容 -->
		<scroll-view class="main_scroll" scroll-y @scroll="handleScroll" :scroll-top="scrollTop" scroll-into-view="viewId">
			<!-- 1. 商品图片区域（移入滚动区） -->
			<view class="product_pic" id="imagesSection">
				<swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#ffffff">
					<swiper-item v-for="(pic, index) in product.images" :key="index">
						<image class="swiper-image" :src="pic.url" mode="widthFix" :alt="product.productName || '商品图片'"></image>
					</swiper-item>
				</swiper>
			</view>

			<!-- 2. 商品详情区域（所有内容都在滚动区） -->
			<view class="product_detail" id="infoSection">
				<!-- 价格信息（详价模块） -->
				<view class="product_price" id="priceSection">
					<text class="price_symbol">￥</text>
					<text class="current_price">{{ Number(product.price).toFixed(2) }}</text>
					<text class="original_price" v-if="product.originalPrice">￥{{ Number(product.originalPrice).toFixed(2) }}</text>
				</view>

				<!-- 商品名称 -->
				<view class="product_name">
					<text class="name">{{ product.productName }}</text>
				</view>

				<!-- 商品规格 -->
				<view class="product_spec" v-if="product.specs">
					<text class="spec_text">规格：{{ product.specs }}</text>
				</view>

				<!-- 商品详情描述 -->
				<view class="product_desc">
					<view class="desc_title">商品详情</view>
					<view class="desc_content" v-if="product.description">
						<text>{{ product.description }}</text>
					</view>
					<!-- 商品详情图（图片模块） -->
					<view class="desc_images" v-if="product.images && product.images.length">
						<image v-for="(img, idx) in product.images" :key="idx" :src="img.url" mode="widthFix" class="detail-img" :alt="`商品详情图${idx + 1}`"></image>
					</view>
				</view>
			</view>

			<view class="bottom_spacer"></view>
		</scroll-view>

		<!-- 底部操作栏（固定） -->
		<view class="footBar">
			<view class="stat" @click="handleCollect">
				<uni-icons :type="isCollected? 'star-filled':'star'" size="40rpx" :color="isCollected ? '#FF3D00' : '#666'"></uni-icons>
				<text>收藏</text>
			</view>
			<view class="car" @click="handleCart">
				<uni-icons type="cart" size="40rpx"></uni-icons>
				<text>购物车</text>
				<view class="cart_count" v-if="getQuantity(product._id) > 0">{{ getQuantity(product._id) }}</view>
			</view>
		
			<view class="add_cart" @click="addToCart">
				<text>加入购物车</text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			product: {},
			isCollected: false,
			// 滚动控制相关
			isScrollUp: false, // 滚动超过阈值：true=显示输入框+菜单，false=显示搜索图标
			lastScrollTop: 0, // 上一次滚动位置
			scrollThreshold: 100, // 触发切换的滚动阈值（rpx）
			scrollTop: 0, // 滚动位置（用于菜单跳转）
			currentMenu: 'info', // 当前选中菜单：info=详情，images=图片，price=详价
			sectionTop: {} // 各模块顶部位置（用于菜单跳转）
		};
	},
	mounted() {
		// 页面加载后获取各模块的顶部位置（用于菜单跳转）
		this.$nextTick(() => {
			this.getSectionTop();
		});
	},
	methods: {
		// 获取购物车商品数量
		getQuantity(productId) {
			const items = this.$store?.state?.cart?.items || [];
			const item = items.find((item) => item._id === productId);
			return item?.quantity || 0;
		},

		// 1. 滚动事件处理：控制搜索框/菜单显隐
		handleScroll(e) {
			const currentScrollTop = e.detail.scrollTop; // 当前滚动位置（px）
			// 转换为 rpx（统一单位计算）
			const currentScrollTopRpx = currentScrollTop * (750 / this.$store.state.msg.systemInfo.windowWidth);

			// 逻辑：向上滚动且超过阈值 → 显示输入框+菜单；向下滚动且低于阈值 → 隐藏
			if (currentScrollTopRpx > this.scrollThreshold && currentScrollTop > this.lastScrollTop) {
				this.isScrollUp = true;
			} else if (currentScrollTopRpx < this.scrollThreshold - 50 && currentScrollTop < this.lastScrollTop) {
				this.isScrollUp = false;
			}

			this.lastScrollTop = currentScrollTop;
		},

		// 2. 手动显示搜索输入框（点击搜索图标触发）
		showSearchInput() {
			this.isScrollUp = true;
			// 聚焦输入框（需延迟，确保DOM已更新）
			setTimeout(() => {
				const input = uni.createSelectorQuery().in(this).select('.search_input');
				input
					.fields({ node: true }, (res) => {
						res.node.focus();
					})
					.exec();
			}, 100);
		},

		// 3. 详情菜单切换 + 滚动到对应模块
		switchMenu(menuKey) {
			this.currentMenu = menuKey;
			// 根据菜单key滚动到对应模块
			switch (menuKey) {
				case 'info':
					this.scrollTop = this.sectionTop.infoSection || 0;
					break;
				case 'images':
					this.scrollTop = this.sectionTop.imagesSection || 0;
					break;
				case 'price':
					this.scrollTop = this.sectionTop.priceSection || 0;
					break;
			}
		},

		// 4. 获取各模块顶部位置（用于菜单跳转）
		getSectionTop() {
			const sections = ['infoSection', 'imagesSection', 'priceSection'];
			sections.forEach((key) => {
				uni.createSelectorQuery()
					.in(this)
					.select(`#${key}`)
					.boundingClientRect((rect) => {
						if (rect) {
							// 转换为px（scroll-top用px单位）
							this.sectionTop[key] = rect.top + this.lastScrollTop - 120; // 减去导航栏高度，避免被遮挡
						}
					})
					.exec();
			});
		},

		// 5. 其他基础功能
		navigateBack() {
			uni.navigateBack({ delta: 1 });
		},
		handleSearchInput(e) {
			uni.navigateTo({
				url: `/pages/searchGood/searchGood?groupId=${this.groupId}`
			});

			// 实际项目中可对接搜索接口
		},
		handleEdit() {
			uni.showToast({ title: '编辑功能待实现', icon: 'none' });
		},
		handleCollect() {
			this.isCollected = !this.isCollected;
			uni.showToast({ title: this.isCollected ? '收藏成功' : '取消收藏', icon: 'none' });
		},
		handleCart() {
			uni.navigateTo({
				url:'/pages/shopcart/shopcart'
			})
			},
		buyImmediately() {
			uni.showToast({ title: '立即购买功能待实现', icon: 'none' });
		},
		addToCart() {
			this.$store.commit('cart/addItem', { ...this.product, quantity: 1 });
			uni.vibrateShort();
			uni.showToast({ title: '加入购物车成功', icon: 'none' });
		}
	},
	onLoad(res) {
		// 接收商品数据
		if (res.product) {
			this.product = JSON.parse(decodeURIComponent(res.product));
			console.log(this.product);
		} else {
			uni.showToast({
				title:'无商品详细信息',
				position:'center'
			})
		uni.navigateBack()
		}
	}
};
</script>

<style lang="scss" scoped>
.page-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	overflow: hidden;
}

/* 1. 导航栏样式：适配滚动切换 */
.navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	padding: 0 30rpx;
	display: flex;
	width: 100%;
	flex-direction: column;
	justify-content: space-between;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	z-index: 100;
	box-sizing: border-box;

	/* 左侧：返回 + 搜索输入框 */
	.navbar_left {
		display: flex;
		flex: 1;
		align-items: center;
		gap: 15rpx;

		.navbar_back {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 50%;
			background-color: rgba(245, 245, 245, 0.8);
		}

		/* 搜索输入框：滚动时显示 */
		.search_input {
			width: 500rpx;
			height: 60rpx;
			padding: 0 20rpx;
			background-color: #fff;
			border-radius: 30rpx;
			font-size: 26rpx;
			color: #333;
		}
	}
	.search_box {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 500rpx;
		height: 60rpx;
		background-color: #fff;
		border-radius: 30rpx;
		font-size: 26rpx;
		color: #333;
	}
	/* 中间：详情菜单（滚动时显示） */
	.detail_menu {
		display: flex;
		gap: 40rpx;
		font-size: 28rpx;
		margin-top: 10rpx;
		margin-left: auto;
		margin-right: auto;

		.menu_item {
			padding: 10rpx 0;
			color: #666;
			position: relative;
			transition: color 0.2s;

			&.active {
				color: #ff3d00;
			}

			/* 选中态下划线 */
			&.active::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 0;
				width: 100%;
				height: 4rpx;
				background-color: #ff3d00;
				border-radius: 2rpx;
			}
		}
	}

	/* 右侧：搜索图标 + 编辑 */
	.navbar_right {
		display: flex;
		align-items: center;
		gap: 20rpx;

		.navbar_search,
		.navbar_edit {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 50%;
			background-color: rgba(245, 245, 245, 0.8);
		}
	}
}

/* 2. 主滚动区：包含图片+所有详情（高度=全屏-导航栏-底部栏） */
.main_scroll {
	width: 100%;
	/* 高度计算：全屏高度 - 导航栏高度(120rpx) - 底部栏高度(120rpx) */
	height: calc(100vh - 120rpx);
	box-sizing: border-box;
}

/* 3. 商品图片区域（移入滚动区后样式调整） */
.product_pic {
	width: 100%;
	background-color: #fff;

	swiper {
		width: 100%;
		/* 图片高度：自适应，保持16:9比例 */
		height: calc(100vh * 0.5);

		swiper-item {
			width: 100%;
			height: 100%;
		}

		.swiper-image {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}

		/* 轮播指示器 */
		.wx-swiper-dots {
			bottom: 100rpx;
			z-index: 10;
		}

		.wx-swiper-dot {
			width: 12rpx;
			height: 12rpx;
			margin: 100rpx 10rpx;
		}
	}
}

/* 4. 商品详情区域（样式优化） */
.product_detail {
	width: 100%;
	padding: 30rpx;
	box-sizing: border-box;
	border-top-left-radius: 50rpx;
	border-top-right-radius:50rpx ;
	position: relative;
	z-index: 20;
	margin-top: -50rpx;
	background-color: #fff;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.5);
  

	/* 价格区域 */
	.product_price {
		display: flex;
		align-items: baseline;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f1f1f1;

		.price_symbol {
			font-size: 28rpx;
			color: #ff3d00;
			margin-right: 5rpx;
		}

		.current_price {
			font-size: 40rpx;
			color: #ff3d00;
			font-weight: bold;
			margin-right: 15rpx;
		}

		.original_price {
			font-size: 26rpx;
			color: #999;
			text-decoration: line-through;
		}
	}

	/* 商品名称 */
	.product_name {
		margin-bottom: 20rpx;

		.name {
			font-size: 34rpx;
			color: #333;
			font-weight: bolder;
			line-height: 1.4;
		}
	}

	/* 商品规格 */
	.product_spec {
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f1f1f1;

		.spec_text {
			font-size: 28rpx;
			color: #666;
		}
	}

	/* 商品描述 */
	.product_desc {
		width: 100%;

		.desc_title {
			font-size: 30rpx;
			color: #333;
			font-weight: bold;
			margin-bottom: 20rpx;
			padding-bottom: 10rpx;
			border-bottom: 1rpx solid #f1f1f1;
		}

		.desc_content {
			font-size: 26rpx;
			color: #666;
			line-height: 1.6;
			margin-bottom: 30rpx;
		}

		/* 详情图片 */
		.desc_images {
			width: 100%;
			display: flex;
			flex-direction: column;
			gap: 15rpx;

			.detail-img {
				width: 100%;
				border-radius: 10rpx;
			}
		}
	}
}

/* 5. 底部留白 */
.bottom_spacer {
	height: 150rpx;
	width: 100%;
}

/* 6. 底部操作栏（固定） */
.footBar {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	height: 120rpx;
	background-color: #fff;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	z-index: 90;
	box-sizing: border-box;

	.stat,
	.car {
		width: 100rpx;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #666;
		gap: 8rpx;
		position: relative;
	}

	.cart_count {
		position: absolute;
		top: 15rpx;
		right: 20rpx;
		width: 36rpx;
		height: 36rpx;
		border-radius: 50%;
		background-color: #ff3d00;
		color: #fff;
		font-size: 22rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.buy_now,
	.add_cart {
		flex: 1;
		height: 80rpx;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		font-weight: 600;
		margin: 0 10rpx;
		transition: all 0.2s;
	}

	.buy_now {
		background-color: #fff;
		color: #ff3d00;
		border: 2rpx solid #ff3d00;
	}

	.add_cart {
		background-color: #ff3d00;
		color: #fff;
	}

	/* 点击反馈 */
	.stat:active,
	.car:active {
		color: #ff3d00;
	}

	.buy_now:active {
		background-color: #fef5f5;
	}

	.add_cart:active {
		background-color: #e63600;
	}
}
</style>
